﻿Imports System.Linq
Imports MNL.Store
Partial Class Details
    Inherits System.Web.UI.Page
    Private dc As MNLDataContext
    Private _partID As Integer
    Const MINSUPPORT As Double = 6 / 100
    Const MINCONFIDENCE As Double = 70 / 100
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Request.QueryString("PartID") IsNot Nothing Then

            Try
                Dim PartID As Integer = Request.QueryString("PartID")
                _partID = PartID
                dc = New MNLDataContext

                Dim thePart = dc.Parts.Where(Function(p) p.PartID = PartID)
                FormView1.DataSource = thePart
                FormView1.DataBind()

            Catch ex As Exception

            End Try
        Else
            Dim mssg As String = "Query string parameter in part details page is missing"
            Response.Redirect(String.Format("ErrorPage.aspx?msg={0}", mssg))
        End If

        'save shipping method
        Session("shippingCost") = GetShippingMethodCost()

        'check if user has rated this part before
        If (Request.Cookies("currentUserRating") IsNot Nothing) Then

            Dim currentUserRating As String = Request.Cookies("currentUserRating").Value

            Dim semicolonIndex As Integer = currentUserRating.IndexOf(":")
            Dim partID = currentUserRating.Substring(0, semicolonIndex)
            Dim userIPAddress = currentUserRating.Substring(semicolonIndex + 1, ((currentUserRating.Length - partID.Length) - 1))

            If HttpContext.Current.Request.UserHostAddress = userIPAddress AndAlso partID = Request.QueryString("PartID") Then

                imgBtnRate.Enabled = False
                partRating.Enabled = False

            End If
        End If

        Recommend() 'recomment parts

    End Sub

    Private Sub Recommend()

        Dim dPartID = Request.QueryString("PartID") 'the partID being viewed by the customer
        Dim apriori As New Apriori(MINSUPPORT, MINCONFIDENCE, dPartID)

        Dim dic_FrequentItemsL1 As Dictionary(Of String, Double) = apriori.GetL1FrequentItems()

        'we now have sets of frequent items and their support. say {a support=> 2, p support=> 4}
        Dim dic_FrequentItems As Dictionary(Of String, Double) = dic_FrequentItemsL1
        Dim dic_Candidates As New Dictionary(Of String, Double)

        Do
            dic_Candidates = apriori.GenerateCandidates(dic_FrequentItems)    ' set {ab -> 4, cd -> 5, ac -> 3}
            dic_FrequentItems = apriori.GetFrequentItems(dic_Candidates, MINSUPPORT)
        Loop Until dic_Candidates.Count <= 0

        Dim dicClosedItemSets As Dictionary(Of String, Dictionary(Of String, Double)) = apriori.GetClosedItemSets
        Dim lstRules = apriori.GenerateRules
        Dim lstStrongRules As List(Of clssRules) = apriori.GetStrongRules(MINCONFIDENCE, lstRules)

        ShowClosedItems(dicClosedItemSets)
        ShowStrongRules(lstStrongRules)
        ShowRecommendedParts(lstStrongRules)
    End Sub

    Protected Sub imgBtnAddPart_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)

        dc = New MNLDataContext
        Dim part = dc.Parts.Where(Function(t) t.PartID = _partID)

        If part.Count > 0 Then

            Profile.ShoppingCart.InsertPart(part.First.PartID, part.First.CategoryID, part.First.Name, part.First.UnitPrice)

            Response.Redirect(AppRelativeVirtualPath + "?PartID=" + _partID.ToString)
        End If

    End Sub

    Protected Sub gvwOrderedParts_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvwOrderedParts.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then

            'get the delete button
            Dim deleteBtn As ImageButton = e.Row.FindControl("btnRemoveFromCart")

            If deleteBtn IsNot Nothing Then
                deleteBtn.OnClientClick = ("return confirm('Are you sure you want to remove this Part?');")
            End If

        End If
    End Sub

    Protected Sub gvwOrderItems_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvwOrderedParts.RowDeleting

        Dim ID As Integer = CInt(gvwOrderedParts.DataKeys(e.RowIndex).Value)
        CurrentUserShoppingCart.DeletePart(ID)
        BindOrderedPartsGrd()
        Response.Redirect(AppRelativeVirtualPath + "?PartID=" + _partID.ToString)
    End Sub

    Public Sub UpdateTotals()
        'update part quantities
        For Each row As GridViewRow In gvwOrderedParts.Rows

            Dim id = Convert.ToInt32(gvwOrderedParts.DataKeys(row.RowIndex)(0))
            Dim quantity = Convert.ToInt32(CType(row.FindControl("txtQuantity"), TextBox).Text)

            Profile.ShoppingCart.UpdatePartQuantity(id, quantity)
        Next

        'show subtotal and total amounts
        lblSubtotal.Text = FormatPrice(Profile.ShoppingCart.Total)
        lblTotal.Text = FormatPrice(Profile.ShoppingCart.Total + GetShippingMethodCost())

    End Sub

    Protected Sub btnUpdateTotals_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateTotals.Click
        UpdateTotals()
    End Sub

    Private Sub BindOrderedPartsGrd()

        Dim OrderedParts = CurrentUserShoppingCart.GetItems()
        If OrderedParts IsNot Nothing AndAlso OrderedParts.Count > 0 Then
            UpdateTotals()
        Else
            panTotals.Visible = False
        End If

        gvwOrderedParts.DataSource = OrderedParts
        gvwOrderedParts.DataBind()


    End Sub

    Protected Function FormatPrice(ByVal price As Object) As String
        Return Convert.ToDecimal(price).ToString("N2") + " " + "£"
    End Function

    Private Function GetShippingMethodCost() As Decimal
        Dim svalue As String = ddlShippingMethods.SelectedValue
        Dim dValue = svalue.Remove(svalue.Length - 1, 1).Trim
        Return dValue
    End Function

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        'bind ordered parts grid
        BindOrderedPartsGrd()

    End Sub

    Protected Sub ddlShippingMethods_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlShippingMethods.SelectedIndexChanged
        UpdateTotals()
        Session("shippingCost") = GetShippingMethodCost()
    End Sub

    Protected Sub imgBtnLiking_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgBtnLiking.Click

        If Request.QueryString("PartID") IsNot Nothing Then

            Try

                Dim PartID As Integer = Request.QueryString("PartID")
                dc = New MNLDataContext
                Dim thePart = dc.Parts.Where(Function(p) p.PartID = PartID)

                If thePart.Count > 0 Then
                    Dim likings As Integer = thePart.First.TotalLikes

                    likings = likings + 1
                    thePart.First.TotalLikes = likings
                    dc.SubmitChanges()
                End If

                imgBtnLiking.Visible = False
                lblLiking.Visible = True
                lblLiking.Text = "You liked this part"
            Catch ex As Exception

            End Try



        End If
    End Sub

    Protected Sub imgBtnRate_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgBtnRate.Click

        If Request.QueryString("PartID") IsNot Nothing Then

            dc = New MNLDataContext
            Dim rating = partRating.CurrentRating
            Dim PartID As Integer = Request.QueryString("PartID")
            Dim thePart = dc.Parts.Where(Function(t) t.PartID = PartID)

            If thePart.Count > 0 Then

                Dim presentRating As Integer = If(thePart.First.TotalRating IsNot Nothing, thePart.First.TotalRating, 0)
                thePart.First.TotalRating = presentRating + rating

                Dim noOfCustomers = If(thePart.First.NoOfRatedCustomers IsNot Nothing, thePart.First.NoOfRatedCustomers, 0)
                thePart.First.NoOfRatedCustomers = noOfCustomers + 1

                Try
                    dc.SubmitChanges()

                Catch ex As Exception

                End Try

                Dim sb As New StringBuilder
                sb.Append(PartID.ToString)
                sb.Append(":")
                sb.Append(HttpContext.Current.Request.UserHostAddress)

                'register in cookie
                Dim cookie1 As New HttpCookie("currentUserRating")
                cookie1.Value = sb.ToString
                cookie1.Expires = DateTime.Now.AddDays(30)
                Response.Cookies.Add(cookie1)

                imgBtnRate.Enabled = False
                partRating.Enabled = False

            End If

        End If

    End Sub

    Private Sub ShowStrongRules(ByVal lstStrongRules As List(Of clssRules))

        For Each rule As clssRules In lstStrongRules

            Dim sb As New StringBuilder
            sb.Append(rule.X)
            sb.Append("-->")
            sb.Append(rule.Y)
            sb.Append("&nbsp;")
            sb.Append("&nbsp;")
            sb.Append("&nbsp;")
            sb.Append("&nbsp;")
            sb.Append("&nbsp;")
            sb.Append("&nbsp;")
            Dim thePercentage As String = String.Format("{0:0.00}", (rule.Confidence * 100)) + "%"
            sb.Append(thePercentage)
            Dim lbl As New Label
            lbl.Font.Bold = True
            lbl.ForeColor = Drawing.Color.Blue
            lbl.Text = sb.ToString + "<br />"
            pnlStronRules.Controls.Add(lbl)

        Next

    End Sub

    Private Sub ShowRecommendedParts(ByVal lstStrongRules As List(Of clssRules))
        Dim partIds As New List(Of Integer)
        Dim dPartId As Integer = Request.QueryString("PartID")
        For Each rule As clssRules In lstStrongRules

            If Not rule.X = dPartId Then 'avoid adding the part in view

                If Not partIds.Contains(rule.X) Then
                    partIds.Add(rule.X)
                End If

            End If


        Next
        dc = New MNLDataContext

        Dim dParts = From p In dc.Parts Where partIds.Contains(p.PartID)

        lstVRecommended.DataSource = dParts
        lstVRecommended.DataBind()

    End Sub
    Private Sub ShowClosedItems(ByVal dicClosedItemSets As Dictionary(Of String, Dictionary(Of String, Double)))

        For Each strItem As String In dicClosedItemSets.Keys

            Dim lbl As New Label
            lbl.Font.Bold = True
            lbl.ForeColor = Drawing.Color.Blue
            lbl.Text = strItem + "<br />"
            pnlCloseItems.Controls.Add(lbl)

        Next

    End Sub


End Class
